package z.ftpc;

import android.app.Activity;
import android.app.AlertDialog;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;

import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.io.CopyStreamEvent;
import org.apache.commons.net.io.CopyStreamListener;

import java.io.BufferedOutputStream;
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class FileActivity extends Activity {


    private final FTPClient client = MainActivity.client;

    private FTPFile[] files;

    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lv = new ListView(this);
        setContentView(lv);

        lv.setOnItemLongClickListener((adapterView, view, i, l) -> {
            popup(adapterView + " " + view + " " + i + " " + l);
            return true;
        });

        client.setCopyStreamListener(createListener());

        lv.setOnItemClickListener((adapterView, view, position, id) -> {
            FTPFile file = files[(int) id];
            String path = file.getName();

            if (file.getType() == 0) {
                String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download";
                popup("开始下载...");


                try {
                    client.setFileType(FTP.BINARY_FILE_TYPE);
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(dir + "/" + path));
                    client.retrieveFile(path, out);
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    popup(e);
                    return;
                }
                popup("下载完成");
            } else {
                try {
                    client.changeWorkingDirectory(path);
                } catch (IOException e) {
                    popup(e);
                }
                startActivity(new Intent(this, getClass()));
            }

        });

        try {
            refresh();
        } catch (IOException e) {
            popup(e);
        }

    }

    private static CopyStreamListener createListener() {
        return new CopyStreamListener() {
            private long megsTotal = 0;

            @Override
            public void bytesTransferred(CopyStreamEvent event) {
                bytesTransferred(event.getTotalBytesTransferred(), event.getBytesTransferred(), event.getStreamSize());
            }

            @Override
            public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
                long megs = totalBytesTransferred / 1000000;
                for (long l = megsTotal; l < megs; l++) {
                    System.err.print("#");
                }
                megsTotal = megs;
            }
        };
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        String[] ss = {"上传", "新建文件夹", "刷新"};
        for (int i = 0; i < ss.length; i++)
            menu.add(Menu.NONE, i, i, ss[i]);
        return true;
    }


    private EditText et;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == 1) {
            et = new EditText(this);
            new AlertDialog.Builder(this).setView(et).setPositiveButton("确定", (dialogInterface, i) -> {
                try {
                    client.makeDirectory(et.getText().toString());
                } catch (IOException e) {
                    popup(e);
                }
            }).show();
            return true;
        }
        if (id == 2) {
            try {
                refresh();
            } catch (IOException e) {
                popup(e);
            }
            return true;
        }
        popup(id + "");
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) return;
        String path = data.getData().getPath();
        popup(path);
        File file = new File(path);

        try {

            client.storeFileStream(file.getName());

            refresh();
        } catch (IOException e) {
            popup(e);
        }

    }


    private void refresh() throws IOException {
        setTitle(client.printWorkingDirectory());
        files = client.listFiles();
        List<Map<String, ?>> items = new ArrayList<>(files.length);

        for (FTPFile file : files) {
            Map<String, Object> item = new HashMap<>();
            item.put("i", file.getType() == 0 ? R.drawable.file : R.drawable.folder);
            item.put("t", file.getName());

            items.add(item);
        }

        lv.setAdapter(new SimpleAdapter(this, items, R.layout.list, new String[]{"i", "t"}, new int[]{R.id.i, R.id.t}));
    }


    @Override
    protected void onResume() {
        super.onResume();
        try {
            client.changeWorkingDirectory(getTitle().toString());
        } catch (IOException e) {
            popup(e);
        }
    }

    private void popup(String tip) {
        Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_LONG).show();
    }

    private void popup(Exception e) {
        popup(e.getMessage());
    }


}
